import React, { Component } from 'react'
import { Card, Button,Table,message,Modal,Form,Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { reqCategoryList,reqAddCategory } from '../../../api'
import {PAGE_SIZE} from '../../../config'

export default class Category extends Component {

  state = {
    categoryList: [],//商品分类列表
    visible: false,//控制弹窗的显示或隐藏
    operType:'',//操作分类的类型
  }
  
  //创建form表单实例
  formRef = React.createRef();

  componentDidMount () {
    //请求商品分类列表
    this.getCategoryList()
  }

  //获取商品分类列表
  getCategoryList = async() => {
    let result = await reqCategoryList()
    const { status, data, msg } = result
    if (status === 0) {
      this.setState({categoryList:data.reverse()})
    } else {
      message.error(msg,1)
    }
  }

  //显示增加分类弹窗的回调
  showAdd = () => {
    this.setState({
      visible: true,
      operType:'add'
    });
  };

  //显示修改分类弹窗的回调
  showUpdate = () => {
    this.setState({
      visible: true,
      operType:'update'
    });
  };

  toAdd =async (values) => {
    let result = await reqAddCategory(values)
    const { status, data, msg } = result
    if (status === 0) {
      message.success('新增商品分类成功', 1)
      let categoryList = [...this.state.categoryList]
      categoryList.unshift(data)//添加分类到列表的前面
      this.setState({categoryList})
    }
    if(status===1) message.error(msg,1)
  }

  //点击确定按钮的回调
  handleOk = () => {
    const { operType } = this.state
    //表单验证
    this.formRef.current.validateFields().then(values => {
      if (operType === 'add') this.toAdd(values);
      if (operType === 'update') console.log('修改分类');
      this.setState({visible: false,});//隐藏弹窗
      this.formRef.current.resetFields();//重置表单
    }).catch(errorInfo => {
      message.error('表单输入错误，请检查',1)
    })
  };

  //点击取消按钮的回调
  handleCancel = () => {
    this.setState({
      visible: false,
    });
    this.formRef.current.resetFields();
  };

  onFinish = (values) => {
    
  }
  
  render () {
    const dataSource = this.state.categoryList
    const { visible, operType } = this.state;

    const columns = [
      {
        title: '分类名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '操作',
        // dataIndex: 'key',//dataIndex存在时，render函数参数是dataIndex的值,不存在时则传递整个对象
        key: 'handle',
        render:(param) => {
          return <Button type='link' onClick={this.showUpdate}>修改分类</Button>
        },
        width: '25%',
        align:'center'
      },
      
    ];
    
    return (
      <div>
        <Card
          extra={<Button type='primary' onClick={this.showAdd}><PlusOutlined />添加</Button>}
        >
          <Table
            dataSource={dataSource}
            columns={columns}
            bordered
            rowKey='_id'
            pagination={{pageSize:PAGE_SIZE}}
          />
        </Card>
        <Modal
          title={operType==='add'?'增加分类':'修改分类'}
          visible={visible}
          okText='确定'
          cancelText='取消'
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form ref={this.formRef}
            initialValues={{
              remember: true,
            }}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="categoryName"
              rules={[
                {
                  required: true,
                  message: '分类名必须输入!',
                },
              ]}
            >
              <Input placeholder="请输入分类名" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
